package com.example.hjt_java_web_homework3.controller;

import com.example.hjt_java_web_homework3.dao.DeviceDao;
import com.example.hjt_java_web_homework3.model.Device;
import com.example.hjt_java_web_homework3.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Li Chun Hei
 * @date 31/10/2025
 * @description
 */
@RestController
@RequestMapping("/api/devices")
public class DeviceServlet extends BaseServlet {

    @Autowired
    private DeviceDao deviceDao;

    @GetMapping("/findAll")
    public List<Device> findAll(){
        return deviceDao.findAll();
    }

    @PostMapping("/save")
    public boolean save(@RequestBody Device device) {
        System.out.println(device.getName());

        return deviceDao.save(device);
    }

    @PutMapping("/update")
    public boolean update(@RequestBody Device device) {
        System.out.println(device.getName());
        System.out.println(device.getId());

        return deviceDao.update(device);
    }

    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable long id) {
        return deviceDao.delete(id);
    }

    private DeviceService deviceService = new DeviceService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String pathInfo = request.getPathInfo();

            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取所有设备
                List<Device> devices = deviceService.getAllDevices();
                sendSuccessResponse(response, devices);
                logger.info("Retrieved all devices, count: {}", devices.size());

            } else if (pathInfo.matches("/\\d+")) {
                // 根据ID获取设备
                Long id = Long.parseLong(pathInfo.substring(1));
                Device device = deviceService.getDeviceById(id);

                if (device != null) {
                    sendSuccessResponse(response, device);
                    logger.info("Retrieved device with id: {}", id);
                } else {
                    sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "Device not found");
                    logger.warn("Device not found with id: {}", id);
                }

            } else if (pathInfo.equals("/types")) {
                // 获取设备类型
                String type = request.getParameter("type");
                if (type != null && !type.isEmpty()) {
                    List<Device> devices = deviceService.getDevicesByType(type);
                    sendSuccessResponse(response, devices);
                    logger.info("Retrieved devices by type: {}, count: {}", type, devices.size());
                } else {
                    sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "Type parameter is required");
                }
            }

        } catch (Exception e) {
            logger.error("Error in device GET request", e);
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//        try {
//            String requestBody = getRequestBody(request);
//            Device device = objectMapper.readValue(requestBody, Device.class);
//
//            if (deviceService.createDevice(device)) {
//                sendSuccessResponse(response, device);
//                logger.info("Created new device: {}", device.getName());
//            } else {
//                sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "Failed to create device or device ID already exists");
//            }
//
//        } catch (Exception e) {
//            logger.error("Error in device POST request", e);
//            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
//        }
//    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String requestBody = getRequestBody(request);
            Device device = objectMapper.readValue(requestBody, Device.class);

            if (deviceService.updateDevice(device)) {
                sendSuccessResponse(response, device);
                logger.info("Updated device: {}", device.getName());
            } else {
                sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "Device not found");
            }

        } catch (Exception e) {
            logger.error("Error in device PUT request", e);
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String pathInfo = request.getPathInfo();
            if (pathInfo != null && pathInfo.matches("/\\d+")) {
                Long id = Long.parseLong(pathInfo.substring(1));

                if (deviceService.deleteDevice(id)) {
                    sendSuccessResponse(response, "Device deleted successfully");
                    logger.info("Deleted device with id: {}", id);
                } else {
                    sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "Device not found");
                }
            } else {
                sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "Invalid device ID");
            }

        } catch (Exception e) {
            logger.error("Error in device DELETE request", e);
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}
